package com.mcr.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcr.reggie.dao.UserMapper;
import com.mcr.reggie.entity.User;
import com.mcr.reggie.service.UserService;
import com.mcr.reggie.utils.MailUtils;
import com.mcr.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MailUtils mailUtils;
    @Override
    public String sentMsgByQQMail(User user) {
        String qqMail = user.getPhone();//获取手机(qq邮箱)号
        if(StringUtils.isNotEmpty(qqMail)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            mailUtils.sendByQQEmail(qqMail,code);//qq邮箱发送验证码
            redisTemplate.opsForValue().set(qqMail,code,5, TimeUnit.MINUTES);
            return code;
        }
        return null;
    }
    @Override
    public User login(Map map, HttpSession session) {
        String qqMail = (String) map.get("phone");
        String code = (String) map.get("code");
        if(code!=null&&code.equals(redisTemplate.opsForValue().get(qqMail))){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,qqMail);
            User user = userMapper.selectOne(queryWrapper);
            if(user==null){
                user=new User();
                user.setPhone(qqMail);
                userMapper.insert(user);
             }
            session.setAttribute("user",user.getId());
            redisTemplate.delete(qqMail);
            return user;
        }
        return null;
    }
}
